package com.wangge.test1.function;

import java.util.Comparator;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;

import com.wangge.test1.Person;

/**
 * 测试java8内置功能接口:
 * 谓词(Predicate),函数(Function),生产者(Supplier),消费者(Consumer),比较器(comparator),非空验证器(Optional)
 * 
 * @author yangqc
 *
 */
public class InnerFunction {
	/**
	 * 谓词 单参数的布尔值函数.negate反转判断
	 */
	@Test
	public void testPredicate() {
		Predicate<String> p = (s) -> s.length() > 3;
		System.out.println(p.test("sdf"));
		System.out.println(p.negate().test("sdf"));
		Predicate<String> p2 = (s) -> s.startsWith("s");
		// and 会生成一个新的Predicate
		Predicate<String> andp3 = p.and(p2);
		System.out.println("Predicate 的 and 用法" + andp3.test("sdf"));
		// or 会生成一个新的Predicate
		Predicate<String> andp4 = p.or(p2);
		System.out.println("Predicate 的 or 用法" + andp4.test("sdf"));
		Predicate<String> emptyPre = String::isEmpty;
		System.out.println("String1234是否为空:" + emptyPre.test("1234"));
		System.out.println("String''是否为空:" + emptyPre.test(""));

	}

	/**
	 * 函数接受单一参数,并输出结果;用andThen进行串联
	 */
	@Test
	public void testFunction() {
		Function<String, Integer> toInteger = Integer::valueOf;
		// 用andThen进行串联
		Function<String, String> backtoString = toInteger.andThen(String::valueOf);
		System.out.println(backtoString.apply("123"));
	}

	/**
	 * 生产者产生一个给定的泛型类型的结果。区别于函数，生产者不接受参数。
	 */
	@Test
	public void testSupplier() {
		Supplier<Person> sup = Person::new;
		System.out.println(sup.get().firstName);
	}

	/**
	 * 消费者 ,接受一个输入变量,不返回结果
	 */
	@Test
	public void testConsumer() {
		Consumer<Person> pconsumer = (p) -> System.out.println(p.firstName);
		Consumer<Person> pconsum1 = pconsumer.andThen((p) -> {
			p.lastName = "sfs";
			System.out.println(p.lastName);
		});
		pconsum1.accept(new Person());
	}

	/**
	 * 比较器 比较大小
	 */
	@Test
	public void testComparator() {
		Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
		Person p1 = new Person("asdf", "zcvd");
		Person p2 = new Person("zsdf", "xxcvd");
		System.out.println(comparator.compare(p1, p2));
	}

	/**
	 * 非空验证器;1.构建:Optional.of(Val)或者Optional.empty();
	 * 
	 */
	@Test
	public void testOptional() {
		Optional<String> option = Optional.of("sdf");
		System.out.println(option.isPresent());
		System.out.println(option.get().length());
		// 当optonal为空时会输出sdf,不为空则输出val
		System.out.println(option.orElse("sdf"));
		Optional<String> option1 = Optional.empty();
		System.out.println(option1.orElse("ssdfdf"));
		// 不为空可进行消费者操作
		option.ifPresent((s) -> System.out.println("消费者1走起:" + s));
		option1.ifPresent((s) -> System.out.println("消费者2走起:" + s));
	}

}
